package com.aiinterview.subjectservice.controller;

import cn.hutool.core.bean.BeanUtil;

import com.aiinterview.common.entity.Result;
import com.aiinterview.common.exception.ValidationException;
import com.aiinterview.model.subject.dto.SubjectCategoryDto;
import com.aiinterview.model.subject.entity.SubjectCategory;
import com.aiinterview.model.subject.vo.SubjectCategoryVo;
import com.aiinterview.subjectservice.service.SubjectCategoryService;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/subject")
@Slf4j
public class SubjectCategoryController {

    @Autowired
    private SubjectCategoryService subjectCategoryService;

    /**
     * 添加分类
     * @param subjectCategoryDto
     * @return
     */
    @PostMapping("/add")
    public Result<String> add(@RequestBody SubjectCategoryDto subjectCategoryDto)  {
       // 创建一个subjectCategory 把subjectCategoryDto转换成subjectCategory
        try {
            Preconditions.checkNotNull(subjectCategoryDto.getCategoryType(), "分类类型不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(subjectCategoryDto.getCategoryName()), "分类名称不能为空");
            Preconditions.checkNotNull(subjectCategoryDto.getParentId(), "分类父级id不能为空");
            SubjectCategory subjectCategory = BeanUtil.copyProperties(subjectCategoryDto, SubjectCategory.class);

            SubjectCategory insert = subjectCategoryService.insert(subjectCategory);
            return Result.ok("ok");
        } catch (Exception e) {
            throw new ValidationException(e.getMessage());
        }
    }

    /**
     * 查询顶层分类
     * @return
     */
    @GetMapping("/getTopCategory")
    public Result<List<SubjectCategoryVo>> getTopCategory(){
        List<SubjectCategory> topCategoryList = subjectCategoryService.getTopCategory();

        // 把subjectCategory转换成subjectCategoryVo
        List<SubjectCategoryVo> subjectCategoryVoList = topCategoryList.stream()
                .map(subjectCategory -> BeanUtil.copyProperties(subjectCategory, SubjectCategoryVo.class))
                .collect(Collectors.toList());

        return Result.ok(subjectCategoryVoList);

    }

    /**
     * 根据顶层分类的ID查询 该顶层分类下的所有分类和标签
     */
    @GetMapping("/getCategoryAll")
    public Result<SubjectCategory> getAllCategoryById(@Param("id") String id){
        List<SubjectCategory> list = subjectCategoryService.getCategoryListByParentId(id);
        log.info("根据顶层分类的ID查询 该顶层分类下的所有分类和标签 list:{}",list);
        return Result.ok(list);
    }


}
